<template>
  <div class="home-wrapper">
    <project-menu :detail="projectDetail"
                  :pid="projectId"></project-menu>
    <div class="filters-wrapper">
      <div class="title total_title">数据趋势
        <div class="fr">
          <el-button type="primary"
                     v-show="chart_wheres.length < 3"
                     @click="addWhereClick"
                     plain
                     size="small"
                     style="width:80px;">增加
          </el-button>
          <el-button type="primary"
                     @click="searchClick"
                     size="small"
                     style="width:80px;">查询</el-button>
        </div>
      </div>
      <el-row v-for="(searchModel, index) in chart_wheres"
              :key="index"
              type="flex"
              align="middle"
              style="flex-wrap: wrap;">
        <div class="form-wrapper">
          <span class="filter-label">账户：</span>
          <el-select v-model="searchModel.accountid"
                     placeholder="请选择"
                     size="small"
                     class="select-wrapper"
                     filterable>
            <el-option v-for="item in accountList"
                       :key="item.id"
                       :label="item.account"
                       :value="item.id" />
          </el-select>
        </div>
        <el-row type="flex"
                align="middle">
          <div class="form-wrapper">
            <span class="filter-label">数据：</span>
            <el-select v-model="searchModel.datatype1"
                       placeholder="请选择"
                       size="small"
                       class="select-wrapper">
              <el-option v-for="item in dataTypes"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id" />
            </el-select>
          </div>
        </el-row>
        <div class="form-wrapper"
             style="margin-right: 10px;">
          <span class="filter-label">时间：</span>
          <el-date-picker v-model="searchModel.time"
                          size="small"
                          type="datetimerange"
                          :picker-options="pickerOptions"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          format="yyyy-MM-dd HH"
                          align="right"
                          :clearable="false" />
        </div>
        <div class="filter-tit"
             v-if="index > 0">
          <el-button type="danger"
                     size="small"
                     @click="delWhereClick(index)"
                     style="width:80px;">删除
          </el-button>
        </div>
      </el-row>
      <div id="myChart"
           style="width: 100%;height: 380px;"></div>
    </div>
  </div>
</template>

<script>
let echarts = require('echarts/lib/echarts')
require('echarts/lib/chart/line')
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/legend')
import {
  dataTypes,
  isAdmin,
  parseTime,
  pageParams
} from '@/settings'
export default {
  data () {
    return {
      jd_search: '',
      month_target_show: true,
      projectId: 0,
      isnotice: false,
      target: '',
      msgs: [],
      totalMsg: 0,
      pageSize: pageParams.pageSize,
      tasktime: '',
      projectDetail: {},
      projectTaskList: [],
      accountList: [],
      dataTypes: [],
      chart_wheres: [{
        projectid: '',
        accountid: '',
        datatype1: 'cost',
        // datatype2: 'cost',
        time: [parseTime(new Date(), '{y}-{m}-{d} 00:00:00'), parseTime(new Date())],
      }],
      message: '',
      pickerOptions: {
        shortcuts: [{
          text: '昨天',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24);
            end.setTime(end.getTime() - 3600 * 1000 * 24);
            start.setHours(0);
            start.setMinutes(0);
            start.setSeconds(0);
            end.setHours(23);
            end.setMinutes(0);
            end.setSeconds(0);
            picker.$emit('pick', [start, end]);
          }
        },
        {
          text: '今天',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime());
            start.setHours(0);
            start.setMinutes(0);
            start.setSeconds(0);
            end.setHours(23);
            end.setMinutes(0);
            end.setSeconds(0);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            start.setHours(0);
            start.setMinutes(0);
            start.setSeconds(0);
            end.setHours(23);
            end.setMinutes(0);
            end.setSeconds(0);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            start.setHours(0);
            start.setMinutes(0);
            start.setSeconds(0);
            end.setHours(23);
            end.setMinutes(0);
            end.setSeconds(0);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            start.setHours(0);
            start.setMinutes(0);
            start.setSeconds(0);
            end.setHours(23);
            end.setMinutes(0);
            end.setSeconds(0);
            picker.$emit('pick', [start, end]);
          }
        }
        ]
      },
      isAdmin: false,
      task: null
      // taskbox: false,
    }
  },
  created () {
    this.projectId = this.$router.currentRoute.params.id
  },
  computed: {
    taskbox: {
      get () {
        return this.task != null
      },
      set (v) {
        if (!v) {
          this.task = null
        }
      }
    }
  },
  mounted () {
    // this.projectId = this.$router.currentRoute.params.id
    this.isAdmin = isAdmin(this.$store.state.user.id_role)
    this.chart_wheres.forEach(ele => {
      ele.projectid = this.projectId
    })
    this.dataTypes = dataTypes
    // console.log('项目详情ID', this.projectId)
    this.loadData()
    this.loadMsg()
  },
  methods: {
    loadData () {
      this.loadDetail()
      this.loadTaskData()
      // 账号列表
      this.$axios.get('/account/list', {
        projectid: this.projectId
      })
        .then(e => {
          // let data = e.data
          console.log('项目账号列表', e.data)
          this.accountList = e.data.items
          this.accountList.splice(0, 0, {
            id: '',
            account: '全部',
          })
        })
      this.searchClick()
    },
    loadTaskData () {
      this.$axios.get('/task/list', {
        projectid: this.projectId,
        time: this.tasktime
      })
        .then(e => {
          // console.log('项目任务列表', e.data)
          if (e.data.items.length > 0) {
            this.projectTaskList = e.data.items[0]
          } else {
            this.projectTaskList = []
          }
        })
    },
    loadMsg (param) {
      if (!param) {
        param = {}
      }
      param['number'] = 5 // 只显示五条记录this.pageSize
      this.$axios.get('/user/message', param)
        .then((e) => {
          // console.log(e)
          this.msgs = e.data.items
          this.totalMsg = e.data.total
        })
    },
    handleCurrentChange (val) {
      // console.log(t, val)
      this.loadMsg({
        page: val
      })
    },
    openNotice (item) {
      if (item.status != 0) {
        this.$alert(item.name, '消息内容')
        return
      }
      this.$confirm(item.name, '消息内容', {
        confirmButtonText: '确认已读',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 发送已读请求
        this.$axios.get('/user/message/read', {
          id: item.id
        }).then(() => {
          let idx = this.msgs.findIndex(e => {
            return e.id == item.id
          })
          if (idx != -1) {
            this.msgs[idx].status = 1
          }
        })
      }).catch(() => { })
    },
    loadDetail () {
      this.$axios.get('/project/detail', {
        projectid: this.projectId
      })
        .then(e => {
          // console.log('项目详情', e.data)
          this.projectDetail = e.data
          if (!this.isAdmin) {
            this.isAdmin = this.projectDetail.id_manager == this.$store.state.user.uid
          }
          if (this.projectDetail.status != 1) {
            this.isAdmin = false
          }
        })
    },
    addWhereClick () {
      if (this.chart_wheres.length >= 3) {
        this.$message('已经添加到最多了')
        return
      }
      this.chart_wheres.push({
        projectid: this.projectId,
        accountid: '',
        datatype1: 'cost',
        // datatype2: 'cost',
        // time: [parseTime(new Date()), parseTime(new Date())],
        time: [parseTime(new Date(), '{y}-{m}-{d} 00:00:00'), parseTime(new Date())],
      })
      // this.initChartWhere(this.chart_wheres[this.chart_wheres.length - 1])
    },
    delWhereClick (idx) {
      this.chart_wheres.splice(idx, 1)
    },
    searchClick () {
      console.log('搜索', this.chart_wheres)
      // 图表数据
      this.$axios.get('/project/chart', {
        type: 'project',
        data: this.chart_wheres
      })
        .then(e => {
          if (JSON.stringify(e.data) != "[]") {
            if (e.data.series.length > 1) {
                e.data.series.forEach(function (item, index) {
                    e.data.xAxis[index].axisPointer.label = {
                        formatter: function (params) {
                            return params.value + (params.seriesData.length ? ' : ' + params
                                    .seriesData[0].data : '');
                        }
                    }
                })
            }
            console.info(e.data);
            let chartData = e.data
            console.log(chartData,78686);
            this.drawLine(chartData)
          }
        })
    },
    saveProjectTarget (target) {
      this.$axios.post('/project/target/save', {
        id: this.projectDetail.id,
        type: target,
        target: this.projectDetail[target]
      })
        .then((e) => {
          this.$message.success(e.msg ? e.msg : '操作成功')
          this.month_target_show = !this.month_target_show;
          // 重新读取数据
          this.loadDetail()
        })
    },
    openTask (item) {
      if (item.completeState == '已完成') {
        this.$alert(item.content, '任务内容', {
          confirmButtonText: '确定'
        })
        return
      }
      this.$confirm(item.content, '任务内容', {
        confirmButtonText: '确认完成',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 发送已读请求
        this.$axios.post('/task/finish', {
          id: item.id
        }).then(() => {
          item.completeState = '已完成'
        })
      }).catch(() => { })
    },
    drawLine (chartData) {
      let myChart = echarts.init(document.getElementById('myChart'))
      let sizeFun = function () {
        myChart.resize()
      }
      window.addEventListener('resize', sizeFun)
      // 绘制图表
      myChart.setOption(chartData, true)
    },
    sendMessageClick () {
      if (this.message == '') {
        this.$message.error('请输入公告内容')
        return
      }
      this.$axios.post('/message/send', {
        projectid: this.projectId,
        content: this.message
      }).then((e) => {
        this.message = ''
        this.$message({
          message: e.msg ? e.msg : '发布成功!',
          type: 'success'
        })
        this.shownoite()
        this.loadMsg()
      })
    },
    openMsg (item) {
      // console.log(item)
      this.task = item
      this.taskbox = true
      if (item.tast_progress == '已完成') {
          this.$alert(item.tast_name, '任务内容', {
              confirmButtonText: '确定'
          })
          return
      }
      this.$confirm(item.tast_name, '任务内容', {
          confirmButtonText: '确认完成',
          cancelButtonText: '取消',
          type: 'info'
      }).then(() => {
          // 发送已读请求
          this.$axios.post('/task/finish', {
              id: item.id
          }).then(() => {
              item.tast_progress = '已完成'
          })
      }).catch(() => {})
    },
    changeTaskStatus (status) {
      // 发送已读请求
      this.$axios.post('/task/finish', {
        id: this.task.id,
        status: status
      }).then((e) => {
        this.task.status = status
        this.task.tast_progress = e.data.new_status // '已完成'
        this.task = null
      })
    },
    monthEdit () {
      this.month_target_show = !this.month_target_show;
    },
    shownoite () {
      this.isnotice = !this.isnotice;
    },
    changeTasktime () {
      console.log('changeTasktime')
      this.loadTaskData()
    }
  }
}
</script>